package com.example.picture_sharing_system;

import androidx.appcompat.app.AppCompatActivity;

import android.app.DownloadManager;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.NetworkOnMainThreadException;
import android.os.Trace;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.tu.loadingdialog.LoadingDailog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;


import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.lang.reflect.Type;

import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import utils.BaseResponse;
import utils.Constants;
import utils.Users;

public class LoginActivity extends AppCompatActivity {

    private EditText edt_username;
    private EditText edt_password;
    private Button btn_login;

    private int userid;
    private TextView tv_toRegister;
    private LoadingDailog loadingDailog;


    private okhttp3.Callback callback = new okhttp3.Callback() {
        @Override
        public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
            if (response.isSuccessful()) {
                final String body = response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Gson gson = new Gson();
                        Type jsonType =
                                new TypeToken<BaseResponse<Users>>() {
                                }.getType();
                        BaseResponse<Users> usersBaseResponse =
                                gson.fromJson(body, jsonType);


                        userid = usersBaseResponse.getData().getUserid();


                        String msg = usersBaseResponse.getMsg();
                        Log.d("TAG", "run: " + msg);
                        if (msg.equals("success")) {
                            Intent intent = new Intent(LoginActivity.this, MainActivity.class);

                            intent.putExtra("userid", userid);
                            startActivity(intent);
                            loadingDailog.hide();
                            loadingDailog.dismiss();
                            Toast.makeText(getApplicationContext(), "登录成功", Toast.LENGTH_LONG).show();

                            finish();
                        } else {
                            loadingDailog.hide();
                            loadingDailog.dismiss();
                            Toast.makeText(getApplicationContext(), "用户名密码错误", Toast.LENGTH_LONG).show();
                        }


                    }
                });
            }
        }

        @Override
        public void onFailure(@NotNull Call call, @NotNull IOException e) {
            e.printStackTrace();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        initData();


        Intent intent = getIntent();
        edt_username.setText(intent.getStringExtra("username"));
        edt_password.setText(intent.getStringExtra("password"));
        Log.d("tag", "onCreate: " + intent.getStringExtra("username"));

        tv_toRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getApplicationContext(), RegisterActivity.class);
                startActivity(intent);
                finish();
            }
        });

        btn_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (edt_password.getText().length() <= 0 || edt_username.getText().length() <= 0) {
                    Toast.makeText(getApplicationContext(), "输入不能为空", Toast.LENGTH_LONG).show();
                    return;
                }
                loadingDailog = new LoadingDailog.Builder(LoginActivity.this)
                        .setMessage("正在登录")
                        .setCancelable(true)
                        .setCancelOutside(true).create();
                loadingDailog.show();

                login();

            }
        });

    }

    public void initData() {
        btn_login = findViewById(R.id.btn_login);
        edt_password = findViewById(R.id.edt_password);
        edt_username = findViewById(R.id.edt_username);
        tv_toRegister = findViewById(R.id.tv_toRegister);
    }

    public void login() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String urlParams
                        = "?username=" + edt_username.getText()
                        + "&password=" + edt_password.getText();

                Request request = new Request.Builder()
                        .url(Constants.LOGIN_URL + urlParams)
                        .get().build();

                try {
                    OkHttpClient client = new OkHttpClient();
                    client.newCall(request).enqueue(callback);
                } catch (NetworkOnMainThreadException ex) {
                    ex.printStackTrace();
                }
            }
        }).start();
    }
}